﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using BestHTTP;
using System;

public class HttpManager : MonoSingleton<HttpManager> {

	private Queue<HttpTask> queue = new Queue<HttpTask>();

	protected override void Init ()
	{
		base.Init ();
		queue.Clear ();
	}

	public void Request(HttpTask request) {
		this.queue.Enqueue (request);
	}

	void Update() {
		if (queue.Count > 0) {
			HttpSend (queue.Dequeue ());
		}
	}

	private void HttpSend(HttpTask task) {
		HTTPRequest request = new HTTPRequest(new System.Uri(task.Url), HTTPMethods.Post, (req, resp) => {
			switch(req.State) {
			case HTTPRequestStates.Finished:
				if (resp.IsSuccess) {
					task.Success(resp.Data);
				} else {
					Debug.LogError(resp.StatusCode + "," + resp.Message);
					task.Fail(emHttpRequestState.ServerError);
				}
				break;
			case HTTPRequestStates.Error:
				task.Fail(emHttpRequestState.Error);
				break;
			case HTTPRequestStates.Aborted:
				task.Fail(emHttpRequestState.Aborted);
				break;
			case HTTPRequestStates.ConnectionTimedOut:
				task.Fail(emHttpRequestState.ConnectionTimedOut);
				break;
			case HTTPRequestStates.TimedOut:
				task.Fail(emHttpRequestState.TimedOut);
				break;
			}
		});
		request.AddHeader ("Validate", EncryptUtils.Base64Encrypt(task.Header));
        request.AddHeader("App-Config", task.APPConfig);
		Debug.Log (task.Header);
		Debug.Log (EncryptUtils.Base64Encrypt(task.Header));
        Debug.Log(task.APPConfig);
        request.RawData = task.Data;
		request.ConnectTimeout = TimeSpan.FromSeconds (2);
		request.Timeout = TimeSpan.FromSeconds (10);
		request.Send ();
	}

}
